package com.lpb.spring.lpbspring.getway.util;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


/** 
 * <p> 
 * RSA公钥/私钥/签名工具包 
 * </p>
 * <p> 
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/> 
 * 由于非对称加密速度极其缓慢，一般文件不使用它来加密而是使用对称加密，<br/> 
 * 非对称加密算法可以用来对对称加密的密钥加密，这样保证密钥的安全也就保证了数据的安全 
 * </p> 
 */
public class RSAUtils {

    private RSAUtils() {
        super();
    }

    /**
     * 加密算法RSA 
     */
    public static final String KEY_ALGORITHM = "RSA";

    /** 
     * 签名算法 
     */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * 获取公钥的key 
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * 获取私钥的key 
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * RSA最大加密明文大小 
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小 
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * <p> 
     * 生成密钥对(公钥和私钥) 
     * </p> 
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Object> genKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * <p> 
     * 用私钥对信息生成数字签名 
     * </p> 
     *
     * @param data 已加密数据
     * @param privateKey 私钥(BASE64编码)
     *
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(getKey(privateKey, PrivateKey.class));
        signature.update(data);
        return encode2base64(signature.sign());
    }

    public static String encode2base64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }


    public static byte[] decode2base64(String base64) {
        return Base64.getDecoder().decode(trim(base64).getBytes(StandardCharsets.UTF_8));
    }
    public static String trim(String str) {
        return str.replaceAll("[\r\n]", "");
    }


    /**
     * <p> 
     * 校验数字签名 
     * </p> 
     *
     * @param data 已加密数据 
     * @param publicKey 公钥(BASE64编码) 
     * @param sign 数字签名 
     *
     * @return
     * @throws Exception
     *
     */
    public static boolean verify(byte[] data, String publicKey, String sign) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(getKey(publicKey, PublicKey.class));
        signature.update(data);
        return signature.verify(decode2base64(sign));
    }

    protected static <T extends Key> T getKey(String keyStr, Class<T> keyClass) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] keyBytes = decode2base64(keyStr);
        Key key;
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        if (keyClass == PublicKey.class) {
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            key = keyFactory.generatePublic(x509KeySpec);
        } else {
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            key = keyFactory.generatePrivate(pkcs8KeySpec);
        }
        return keyClass.cast(key);
    }

    /**
     * <P> 
     * 私钥解密 
     * </p> 
     *
     * @param encryptedData 已加密数据 
     * @param privateKey 私钥(BASE64编码) 
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {
        return cryptByKey(encryptedData, privateKey, false, Cipher.DECRYPT_MODE);
    }

    protected static byte[] cryptByKey(byte[] data, String keyStr, boolean isPublic, int mode) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {
        Key key;
        if (isPublic) {
            key = getKey(keyStr, PublicKey.class);
        } else {
            key = getKey(keyStr, PrivateKey.class);
        }
        Cipher cipher = Cipher.getInstance(key.getAlgorithm());
        cipher.init(mode, key);
        return doFinal(cipher, data, mode);
    }

    /**
     * <p> 
     * 公钥解密 
     * </p> 
     *
     * @param encryptedData 已加密数据 
     * @param publicKey 公钥(BASE64编码) 
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {
        return cryptByKey(encryptedData, publicKey, true, Cipher.DECRYPT_MODE);
    }

    private static byte[] doFinal(Cipher cipher, byte[] data, int mode) throws BadPaddingException, IllegalBlockSizeException, IOException {
        int inputLen = data.length;
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        int block = mode == Cipher.DECRYPT_MODE ? MAX_DECRYPT_BLOCK : MAX_ENCRYPT_BLOCK;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > block) {
                    cache = cipher.doFinal(data, offSet, block);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * block;
            }
            return out.toByteArray();
        }
    }

    /**
     * <p> 
     * 公钥加密 
     * </p> 
     *
     * @param data 源数据 
     * @param publicKey 公钥(BASE64编码) 
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException {
        return cryptByKey(data, publicKey, true, Cipher.ENCRYPT_MODE);
    }

    /**
     * <p> 
     * 私钥加密 
     * </p> 
     *
     * @param data 源数据 
     * @param privateKey 私钥(BASE64编码) 
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
        return cryptByKey(data, privateKey, false, Cipher.ENCRYPT_MODE);
    }

    /**
     * <p> 
     * 获取私钥 
     * </p> 
     *
     * @param keyMap 密钥对 
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return encode2base64(key.getEncoded());
    }

    /**
     * <p> 
     * 获取公钥 
     * </p> 
     *
     * @param keyMap 密钥对 
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return encode2base64(key.getEncoded());
    }

}  